# apps/questions/serializers.py
from rest_framework import serializers
from .models import Question, QuestionTag
from apps.users.serializers import UserSerializer
from apps.subjects.serializers import SubjectSerializer
from apps.tags.serializers import TagSerializer
from apps.tags.models import Tag
from ..subjects.models import Subject


class QuestionTagWriteSerializer(serializers.ModelSerializer):
    tag_id = serializers.PrimaryKeyRelatedField(
        queryset=Tag.objects.all(),
        source='tag'
    )

    class Meta:
        model = QuestionTag
        fields = ['tag_id']

class QuestionSerializer(serializers.ModelSerializer):
    creator = UserSerializer(read_only=True)
    subject = SubjectSerializer(read_only=True)
    subject_id = serializers.PrimaryKeyRelatedField(
        queryset=Subject.objects.all(),
        write_only=True,
        source='subject'
    )
    tags = TagSerializer(many=True, read_only=True)
    tag_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False
    )

    class Meta:
        model = Question
        fields = [
            'id', 'title', 'question_type', 'difficulty',
            'analysis', 'reference', 'subject', 'subject_id',
            'creator', 'status', 'view_count', 'use_count',
            'created_at', 'updated_at', 'tags', 'tag_ids'
        ]
        read_only_fields = ['creator', 'view_count', 'use_count', 'created_at', 'updated_at']

    def create(self, validated_data):
        tag_ids = validated_data.pop('tag_ids', [])
        request = self.context.get('request')
        validated_data['creator'] = request.user

        question = Question.objects.create(**validated_data)

        # 关联标签
        self._set_tags(question, tag_ids)

        return question

    def update(self, instance, validated_data):
        tag_ids = validated_data.pop('tag_ids', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        if tag_ids is not None:
            self._set_tags(instance, tag_ids)

        return instance

    def _set_tags(self, question, tag_ids):
        QuestionTag.objects.filter(question=question).delete()
        tags = Tag.objects.filter(id__in=tag_ids)
        for tag in tags:
            QuestionTag.objects.create(question=question, tag=tag)
            tag.used_count = Tag.objects.filter(questiontag__question=question).count()
            tag.save()